package facade;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

public class Controller extends Graphic implements ActionListener{
	
	static Socket socket = null;
	static String string=null;	
	static ObjectInputStream in = null;
	static ObjectOutputStream out = null;
	static boolean Joinflag=true;
	static boolean Editingflag=false;
	static int x10;
	protected String command="";
	static boolean Closesocket=true;
	private static final String SERVER_IP = "127.0.0.1";
    private static final int SERVER_PORT = 7002;

	public Controller() throws IOException,NullPointerException{
		setActionListeners();
		CreateSocket();
		ClientTextArea.addCaretListener(new CaretListener() {
				public void caretUpdate(CaretEvent arg0) {
				try {
					if(Editingflag)carryon1();
				} catch (IOException e) {
					e.printStackTrace();
				}	
				}
			});
        while(Joinflag){        
        	carryon();}
	}
	private void setActionListeners()  throws IOException,NullPointerException {
		
		LeaveSession.addActionListener(this);
		StopEditing.addActionListener(this);
		StartEditing.addActionListener(this);
		JoinSession.addActionListener(this);
		Exit.addActionListener(this);
				
	}
	public void actionPerformed(ActionEvent action)	{
		command=(String)action.getActionCommand();     //action listener's result is stored in the command string
		
		if(command.equalsIgnoreCase("Join The Session")){
			Editingflag=false;
			Joinflag=true;
			  try{
				  if(out==null){out=new ObjectOutputStream(socket.getOutputStream());}
		      if (in == null) { in = new ObjectInputStream(socket.getInputStream());}
			  out.writeObject(new SerializedMessage(ClientTextArea,Joinflag,Editingflag));
			  out.flush();} catch (Exception ex) {
		            System.out.println("Error: " + ex);
		        }
		}
		else if(command.equalsIgnoreCase("Start Editing")){
			Editingflag=true;
			Joinflag=true;
		}
		else if(command.equalsIgnoreCase("Stop Editing")){
			//System.out.println("Editingflag is off");
			Editingflag=false;
			Joinflag=true;
		}
		else if(command.equalsIgnoreCase("Leave The Session")){
			Editingflag=false;
			Joinflag=false;
			CloseSocket();
		}
		else if(command.equalsIgnoreCase("Exit")){
			Editingflag=false;
			Joinflag=false;
			CloseSocket();
			System.exit(0);
		}
	}
	public static void CloseSocket(){
		try {
			out.writeObject(new SerializedMessage(ClientTextArea,Joinflag,Editingflag));
			out.flush();
			in.close();
			out.close();
			socket.close();
			System.out.println("Disconnected to server!");
		} catch (IOException e) {
		//	e.printStackTrace();
		}
	}
	public static void CreateSocket() {
		try {
			socket = new Socket(SERVER_IP, SERVER_PORT);
			System.out.println("Connected to server!");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	public static void carryon(){
        try {
            if(out==null){out=new ObjectOutputStream(socket.getOutputStream());}
            if (in == null) {in = new ObjectInputStream(socket.getInputStream());}
            SerializedMessage message = (SerializedMessage) in.readObject();
                ClientTextArea.setText(message.getMessage());

        } catch (Exception ex) {
            System.out.println("Error: " + ex);
        }
    }
	public static void carryon1() throws IOException{
		  if(out==null){out=new ObjectOutputStream(socket.getOutputStream());}
		  if (in == null) { in = new ObjectInputStream(socket.getInputStream());}
		  out.writeObject(new SerializedMessage(ClientTextArea,true,Editingflag));
		  out.flush();
	}
}
